<template>

      
      <!-- 右侧内容区域 -->
      <div class="content-container">
        <div class="search-container">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="转移单号码">
              <el-input v-model="searchFormData.allotCode" placeholder="请输入转移单编号"></el-input>
            </el-form-item>
            <el-form-item label="转移单名称">
              <el-input v-model="searchFormData.allotName" placeholder="请输入转移单名称"></el-input>
            </el-form-item>
            <el-form-item label="转移单类型">
              <el-select v-model="searchFormData.allotType" placeholder="请选择转移单类型" style="width: 180px;">
                <el-option label="内部转移" value="内部转移"></el-option>
                <el-option label="外部转移" value="外部转移"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="table-container">
          <div class="table-header">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
          </div>

          <el-table
            ref="tableRef"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            row-key="allotCode"
            border
            stripe
            v-loading="loading"
            element-loading-text="加载中..."
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="allotCode" label="转移单号码" width="180" />
            <el-table-column prop="allotName" label="转移单名称" width="180" />
            <el-table-column prop="allotType" label="转移单类型" width="120" />
            <el-table-column prop="isDelivery" label="是否配送" width="120">
              <template #default="scope">
                <span>{{ scope.row.isDelivery === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="allotDate" label="转移日期" width="120" />
            <el-table-column prop="status" label="单据状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="descs" label="备注" />
            <el-table-column label="操作" width="300">
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row.id || scope.row.ID || scope.row.Id || scope.row.allotCode)">删除</el-button>
                <el-button 
                  v-if="scope.row.status === 1" 
                  size="small" 
                  type="success" 
                  @click="handleDeploy(scope.row)"
                >执行上架</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
 
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加转移单' : (deployMode ? '执行上架' : '编辑转移单')"
      width="800px"
      @close="resetForm"
      :close-on-click-modal="false"
      class="allot-dialog custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="demo-ruleForm"
        label-position="left"
      >
        <el-form-item label="转移单号码" prop="allotCode" required>
          <div class="code-input-container">
            <el-input 
              v-model="formData.allotCode" 
              placeholder="请输入转移单号码" 
              :disabled="dialogType === 'edit' || autoGenerate"
            ></el-input>
            <div class="auto-generate-switch" v-if="dialogType === 'add'">
              <span class="switch-label">{{ autoGenerate ? '自动生成' : '手动输入' }}</span>
              <el-switch
                v-model="autoGenerate"
                class="ml-10"
                active-color="#13ce66"
                @change="handleAutoGenerateChange"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="转移单名称" prop="allotName" required>
          <el-input v-model="formData.allotName" placeholder="请输入转移单名称"></el-input>
        </el-form-item>
        <el-form-item label="转移单类型" required>
          <div class="radio-container">
            <el-radio-group v-model="formData.allotType">
              <el-radio label="内部转移"></el-radio>
              <el-radio label="外部转移"></el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="转移日期" prop="allotDate" required>
          <el-date-picker
            v-model="formData.allotDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.descs"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <!-- 物料列表 -->
      <div v-if="dialogType === 'edit'" class="materials-container">
        <div class="materials-header">
          <h3>物料清单</h3>
          <div class="materials-actions">
            <el-button type="primary" size="small" @click="handleAddMaterial">添加物料</el-button>
            <el-button type="danger" size="small" @click="handleBatchDeleteMaterial">批量删除</el-button>
          </div>
        </div>
        
        <el-table
          ref="materialTableRef"
          :data="materialsList"
          style="width: 100%"
          @selection-change="handleMaterialSelectionChange"
          row-key="materialId"
          border
          stripe
          v-loading="materialsLoading"
          element-loading-text="加载中..."
          max-height="300"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="materialCode" label="产品编码" width="150" />
          <el-table-column prop="materialName" label="产品名称" width="180" />
          <el-table-column prop="specification" label="规格型号" width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="transferSource" label="产品类型" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleDeleteMaterial(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="materials-pagination">
          <el-pagination
            v-model:current-page="materialsPagination.currentPage"
            v-model:page-size="materialsPagination.pageSize"
            :page-sizes="[5, 10, 20]"
            layout="total, sizes, prev, pager, next"
            :total="materialsPagination.total"
            @size-change="handleMaterialsSizeChange"
            @current-change="handleMaterialsCurrentChange"
            small
          />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="btn-cancel">关闭</el-button>
          <el-button 
            type="primary" 
            @click="submitForm" 
            class="btn-save"
          >{{ deployMode ? '提交上架' : (dialogType === 'add' ? '提交' : '保存') }}</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 添加单行物料对话框 -->
    <el-dialog
      v-model="singleMaterialDialogVisible"
      title="添加转移单行"
      width="1000px"
      :close-on-click-modal="false"
      class="single-material-dialog custom-dialog"
    >
      <el-form :model="singleMaterialForm" label-width="100px" label-position="left">
        <el-form-item label="产品物料" required>
          <div class="material-select-container">
            <el-input v-model="singleMaterialForm.materialName" placeholder="选择产品物料" readonly></el-input>
            <el-button type="primary" @click="openMaterialSelector">
              <el-icon><Search /></el-icon>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="产品物料名称">
          <el-input v-model="singleMaterialForm.materialName" placeholder="产品物料名称" disabled></el-input>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="singleMaterialForm.specification" type="textarea" :rows="2" placeholder="规格型号" disabled></el-input>
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="singleMaterialForm.unit" placeholder="单位" disabled></el-input>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="singleMaterialForm.batchNo" placeholder="批次号"></el-input>
        </el-form-item>
        <el-form-item label="转移数量" required>
          <el-input-number 
            v-model="singleMaterialForm.quantity" 
            :min="1" 
            :max="10000" 
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="singleMaterialForm.remark" type="textarea" :rows="3" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="singleMaterialDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddSingleMaterial">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 产品选择对话框 -->
    <el-dialog
      v-model="materialDialogVisible"
      title="选择产品"
      width="1000px"
      :close-on-click-modal="false"
      class="material-dialog custom-dialog"
    >
      <div class="material-dialog-container">
        <!-- 左侧产品类型树 -->
        <div class="material-type-tree">
          <div class="tree-header">
            <h3>产品类型</h3>
            <el-input
              v-model="treeFilterText"
              placeholder="搜索类型"
              clearable
              prefix-icon="Search"
              size="small"
            />
          </div>
          <div class="tree-content">
            <el-tree
              ref="materialTypeTreeRef"
              :data="materialTypeTree"
              :props="{ label: (data) => data.name || data.classifyName || '未命名', children: 'children' }"
              node-key="id"
              highlight-current
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              v-loading="treeLoading"
            />
          </div>
        </div>
        
        <!-- 右侧产品列表 -->
        <div class="material-list-container">
          <div class="material-search">
            <el-form :inline="true">
              <el-form-item label="产品编码">
                <el-input v-model="materialSearchForm.materialCode" placeholder="请输入产品编码" clearable></el-input>
              </el-form-item>
              <el-form-item label="产品名称">
                <el-input v-model="materialSearchForm.materialName" placeholder="请输入产品名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="批次">
                <el-input v-model="materialSearchForm.batch" placeholder="请输入批次" clearable></el-input>
              </el-form-item>
              <el-form-item label="仓库名称">
                <el-input v-model="materialSearchForm.repositoryName" placeholder="请输入仓库名称" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchMaterials">搜索</el-button>
                <el-button @click="resetMaterialSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <el-table
            ref="selectMaterialTableRef"
            :data="availableMaterials"
            style="width: 100%"
            @row-click="handleMaterialRowClick"
            highlight-current-row
            row-key="materialId"
            border
            stripe
            v-loading="materialSearchLoading"
            element-loading-text="搜索中..."
            max-height="350"
          >
            <el-table-column type="radio" width="55" />
            <el-table-column prop="materialCode" label="产品编码" width="150" />
            <el-table-column prop="materialName" label="产品名称" width="180" />
            <el-table-column prop="specification" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="batchNo" label="批次号" width="120" />
            <el-table-column prop="stockQuantity" label="库存数量" width="100" />
            <el-table-column prop="stockLocation" label="库存位置" />
          </el-table>
          
          <div class="materials-pagination">
            <el-pagination
              v-model:current-page="materialSearchPagination.currentPage"
              v-model:page-size="materialSearchPagination.pageSize"
              :page-sizes="[5, 10, 20]"
              layout="total, sizes, prev, pager, next"
              :total="materialSearchPagination.total"
              @size-change="handleMaterialSearchSizeChange"
              @current-change="handleMaterialSearchCurrentChange"
              small
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectMaterial">确定</el-button>
        </div>
      </template>
    </el-dialog>

</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 表格数据
const tableData = ref([])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单数据
const searchFormData = reactive({
  allotCode: '',
  allotName: '',
  allotType: '',
  materialTypeId: null // 添加产品类型ID
})

// 产品类型树相关
const materialTypeTree = ref([])
const materialTypeTreeRef = ref(null)
const treeLoading = ref(false)
const treeFilterText = ref('')
const currentMaterialTypeId = ref(null)

// 监听树形过滤文本变化
watch(treeFilterText, (val) => {
  materialTypeTreeRef.value?.filter(val)
})

// 树形节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return (data.name || data.classifyName || '').includes(value)
}

// 树形节点点击事件
const handleNodeClick = (data) => {
  console.log('选中的产品类型:', data)
  currentMaterialTypeId.value = data.id
  materialSearchForm.materialTypeId = data.id
  materialSearchForm.flatsMaterial = data.name || data.classifyName // 使用树节点的名称
  searchMaterials()
}

// 获取产品类型树数据
const fetchMaterialTypeTree = async () => {
  try {
    treeLoading.value = true
    const response = await axios.get('/api/Allot/GetMaterialTypeList')
    
    if (response.data && response.data.data && Array.isArray(response.data.data)) {
      materialTypeTree.value = response.data.data
    } else if (response.data && Array.isArray(response.data)) {
      materialTypeTree.value = response.data
    } else {
      materialTypeTree.value = []
      console.error('获取产品类型树数据格式不正确:', response.data)
    }
  } catch (error) {
    console.error('获取产品类型树数据出错:', error)
    ElMessage.error('获取产品类型树数据出错，请稍后重试')
    materialTypeTree.value = []
  } finally {
    treeLoading.value = false
  }
}

// 新增/编辑表单数据
const formData = reactive({
  id: null,
  allotCode: '',
  allotName: '',
  allotType: '内部转移',
  isDelivery: 0,
  allotDate: new Date().toISOString().split('T')[0],
  status: 0, // 默认为草稿状态
  descs: ''
})

// 表单校验规则
const formRules = reactive({
  allotCode: [
    { required: true, message: '请输入转移单号码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  allotName: [
    { required: true, message: '请输入转移单名称', trigger: 'blur' }
  ],
  allotType: [
    { required: true, message: '请选择转移单类型', trigger: 'change' }
  ],
  allotDate: [
    { required: true, message: '请选择转移日期', trigger: 'change' }
  ]
})

// 引用
const tableRef = ref(null)
const formRef = ref(null)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const autoGenerate = ref(true)
const deployMode = ref(false) // 是否为执行上架模式

// 选中行的ID数组
const selectedIds = ref([])

// 状态映射
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已上架',
    3: '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return typeMap[status] || ''
}

// 表格选择变化
const handleSelectionChange = (rows) => {
  console.log('选中行变化:', JSON.stringify(rows));
  
  // 更新选中的ID数组
  selectedIds.value = [];
  
  if (rows && rows.length > 0) {
    rows.forEach(row => {
      // 获取ID
      let rowId = null;
      
      if (row.id !== undefined && row.id !== null) rowId = row.id;
      else if (row.ID !== undefined && row.ID !== null) rowId = row.ID;
      else if (row.Id !== undefined && row.Id !== null) rowId = row.Id;
      else rowId = row.allotCode || '';
      
      if (rowId !== '') {
        selectedIds.value.push(rowId);
      }
    });
  }
  
  console.log('选中ID数组:', selectedIds.value);
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchData()
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
  fetchData()
}

// 搜索
const search = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索条件
const reset = () => {
  Object.keys(searchFormData).forEach(key => {
    searchFormData[key] = ''
  })
  search()
}

// 获取数据
const fetchData = async () => {
  try {
    // 显示加载状态
    loading.value = true
    
    // 构建请求参数
    const params = {
      informCode: searchFormData.allotCode || '',
      allotName: searchFormData.allotName || '',
      allotType: searchFormData.allotType || '',
      materialTypeId: searchFormData.materialTypeId || null,
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    // 调用API
    const response = await axios.post('/api/Allot/GetAllot', params)
    
    // 处理响应数据
    console.log('API响应数据:', response.data);
    
    // 根据实际API响应格式调整
    if (response.data && response.data.rows) {
      // 确保每条数据有唯一标识
      const processedData = response.data.rows.map(item => {
        // 如果没有id，使用allotCode作为唯一标识
        if (item.id === undefined || item.id === null) {
          item.id = item.allotCode || `id_${Math.random().toString(36).substr(2, 9)}`;
        }
        return item;
      });
      
      tableData.value = processedData;
      pagination.total = response.data.total || 0;
    } else if (response.data && response.data.data) {
      // 确保每条数据有唯一标识
      const processedData = (response.data.data.rows || []).map(item => {
        // 如果没有id，使用allotCode作为唯一标识
        if (item.id === undefined || item.id === null) {
          item.id = item.allotCode || `id_${Math.random().toString(36).substr(2, 9)}`;
        }
        return item;
      });
      
      tableData.value = processedData;
      pagination.total = response.data.data.total || 0;
    } else {
      // 如果不符合预期格式，尝试直接使用
      const dataArray = Array.isArray(response.data) ? response.data : [];
      // 确保每条数据有唯一标识
      const processedData = dataArray.map(item => {
        // 如果没有id，使用allotCode作为唯一标识
        if (item.id === undefined || item.id === null) {
          item.id = item.allotCode || `id_${Math.random().toString(36).substr(2, 9)}`;
        }
        return item;
      });
      
      tableData.value = processedData;
      pagination.total = processedData.length;
    }
    
    // 清空选中项
    if (tableRef.value) {
      tableRef.value.clearSelection();
    }
    selectedIds.value = [];
  } catch (error) {
    console.error('获取数据出错:', error)
    ElMessage.error('获取数据出错，请稍后重试')
    tableData.value = []
    pagination.total = 0
  } finally {
    // 隐藏加载状态
    loading.value = false
  }
}

// 处理自动生成开关变化
const handleAutoGenerateChange = (val) => {
  if (val) {
    // 如果开启自动生成，立即生成编号
    generateAllotCode()
  } else {
    // 如果关闭自动生成，清空编号
    formData.allotCode = ''
  }
}

// 生成转移单编号
const generateAllotCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  formData.allotCode = `TR${year}${month}${day}${hours}${minutes}${seconds}`
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  if (autoGenerate.value) {
    generateAllotCode()
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  if (!row && selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
  
  const editRow = row || selectedRows.value[0]
  dialogType.value = 'edit'
  deployMode.value = false // 设置为编辑模式
  
  Object.keys(formData).forEach(key => {
    formData[key] = editRow[key]
  })
  
  // 设置转移单编号不可修改
  autoGenerate.value = false
  dialogVisible.value = true
  
  // 加载物料数据
  await fetchMaterials()
}

// 单个删除方法 - 接收ID
const handleDelete = async (id) => {
  if (!id) {
    ElMessage.warning('无效的记录ID');
    return;
  }

  try {
    await ElMessageBox.confirm(
      '确认删除此记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    console.log("删除单个ID:", id);
    
    // 调用删除API
    const response = await axios.post(`/api/Allot/DelAllot?ids=${id}`);
    
    // 删除成功
    ElMessage.success('删除成功');
    
    // 重新加载数据
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 批量删除方法 - 使用选中的IDs
const handleBatchDelete = async () => {
  console.log('当前选中ID:', selectedIds.value);
  
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录进行删除');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedIds.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 转换为逗号分隔的字符串
    const ids = selectedIds.value.join(',');
    console.log("批量删除ID字符串:", ids);
    
    // 调用删除API
    const response = await axios.post(`/api/Allot/DelAllot?ids=${ids}`);
    
    // 删除成功
    ElMessage.success('删除成功');
    
    // 重新加载数据
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.assign(formData, {
    id: 0,
    allotCode: '',
    allotName: '',
    allotType: '内部转移',
    isDelivery: 0,
    allotDate: new Date().toISOString().split('T')[0],
    status: 0, // 默认为草稿状态
    descs: ''
  })
  
  autoGenerate.value = true
  deployMode.value = false // 重置上架模式
  
  if (autoGenerate.value) {
    generateAllotCode()
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return false
    
    // 显示加载状态
    loading.value = true
    
    // 确保表单数据完整
    const submitData = {
      id: dialogType.value === 'add' ? 0 : formData.id,
      allotCode: formData.allotCode,
      allotName: formData.allotName || '',
      allotType: formData.allotType,
      isDelivery: formData.isDelivery || 0,
      allotDate: formData.allotDate,
      status: dialogType.value === 'add' ? 1 : (deployMode.value ? 2 : 1), // 新增:待审核, 上架:已上架, 编辑:待审核
      descs: formData.descs || ''
    }
    
    if (dialogType.value === 'add') {
      // 新增
      if (autoGenerate.value && !submitData.allotCode) {
        // 如果启用了自动生成但没有编号，生成编号
        generateAllotCode()
        submitData.allotCode = formData.allotCode
      }
      
      console.log('提交的数据:', submitData)
      // 调用新增API
      const response = await axios.post('/api/Allot/CreateAllot', submitData)
      
      ElMessage.success('添加成功')
    } else if (deployMode.value) {
      // 执行上架
      const response = await axios.post('/api/Allot/UpdateAllot', submitData)
      
      ElMessage.success('上架成功')
    } else {
      // 编辑
      // 调用编辑API
      const response = await axios.post('/api/Allot/UpdateAllot', submitData)
      
      ElMessage.success('修改成功')
    }
    
    // 关闭对话框
    dialogVisible.value = false
    
    // 重新加载数据
    fetchData()
  } catch (error) {
    console.error('提交表单出错:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    // 隐藏加载状态
    loading.value = false
  }
}

// 添加加载状态
const loading = ref(false)

// 物料相关数据
const materialsList = ref([])
const selectedMaterialIds = ref([])
const materialsLoading = ref(false)
const materialDialogVisible = ref(false)
const singleMaterialDialogVisible = ref(false)
const materialTableRef = ref(null)
const selectMaterialTableRef = ref(null)
const availableMaterials = ref([])
const selectedMaterial = ref(null)
const materialSearchLoading = ref(false)

// 物料分页配置
const materialsPagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 物料搜索分页配置
const materialSearchPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 物料搜索表单
const materialSearchForm = reactive({
  materialCode: '',
  materialName: '',
  materialTypeId: null, // 添加产品类型ID
  batch: '', // 批次
  repositoryName: '', // 仓库名称
  flatsMaterial: '' // 产品类型名称
})

// 物料选择变化
const handleMaterialSelectionChange = (rows) => {
  selectedMaterialIds.value = rows.map(row => row.materialId)
}

// 物料行点击事件
const handleMaterialRowClick = (row) => {
  selectedMaterial.value = row
  selectMaterialTableRef.value?.setCurrentRow(row)
}

// 物料分页处理
const handleMaterialsSizeChange = (size) => {
  materialsPagination.pageSize = size
  fetchMaterials()
}

const handleMaterialsCurrentChange = (current) => {
  materialsPagination.currentPage = current
  fetchMaterials()
}

// 物料搜索分页处理
const handleMaterialSearchSizeChange = (size) => {
  materialSearchPagination.pageSize = size
  searchMaterials()
}

const handleMaterialSearchCurrentChange = (current) => {
  materialSearchPagination.currentPage = current
  searchMaterials()
}

// 获取物料数据
const fetchMaterials = async () => {
  if (dialogType.value !== 'edit' || !formData.id) return
  
  try {
    materialsLoading.value = true
    
    // 调用API获取物料列表
    const response = await axios.get('/api/Allot/GetAllotMaterialListByAllotId?allotId=' + formData.id)
    console.log(response);
    
    if (response ) {
      // 处理返回的数据
      materialsList.value = response.data.data.map(item => ({
        materialId: item.id || item.materialId,
        materialCode: item.materialCode,
        materialName: item.materialName,
        specification: item.specification,
        unit: item.flats, // 使用safetyStock作为单位
        quantity: item.num, // 使用num作为数量
        transferSource:  item.flatsMaterial, // 使用flats或flatsMaterial作为来源
        isHighValue: item.isHighValue,
        isLock: item.isLock,
        isBatch: item.isBatch
      }))
    } else {
      materialsList.value = []
    }
    
    // 清空选中项
    if (materialTableRef.value) {
      materialTableRef.value.clearSelection()
    }
    selectedMaterialIds.value = []
  } catch (error) {
    console.error('获取物料数据出错:', error)
    ElMessage.error('获取物料数据出错，请稍后重试')
    materialsList.value = []
  } finally {
    materialsLoading.value = false
  }
}

// 添加物料
const handleAddMaterial = () => {
  // 重置单行物料表单
  Object.keys(singleMaterialForm).forEach(key => {
    singleMaterialForm[key] = key === 'quantity' ? 1 : null
  })
  
  // 打开单行物料对话框
  singleMaterialDialogVisible.value = true
}

// 打开物料选择器
const openMaterialSelector = () => {
  // 重置搜索条件
  resetMaterialSearch()
  // 加载产品类型树数据
  fetchMaterialTypeTree()
  // 打开物料选择对话框
  materialDialogVisible.value = true
  // 搜索可用物料
  searchMaterials()
}

// 物料搜索
const searchMaterials = async () => {
  try {
    materialSearchLoading.value = true
    
    // 构建请求参数
    const params = {
      materialCode: materialSearchForm.materialCode || '',
      materialName: materialSearchForm.materialName || '',
      materialTypeId: materialSearchForm.materialTypeId || null,
      batch: materialSearchForm.batch || '',
      repositoryName: materialSearchForm.repositoryName || '',
      flatsMaterial: materialSearchForm.flatsMaterial || '',
      pageIndex: materialSearchPagination.currentPage,
      pageSize: materialSearchPagination.pageSize
    }
    
    // 调用API搜索物料
    const response = await axios.post('/api/Allot/GetMaterial', params)
    console.log(response);
    
    if (response.data && response.data.rows) {
      availableMaterials.value = response.data.rows
      materialSearchPagination.total = response.data.total || 0
    } else if (response.data && response.data.data) {
      availableMaterials.value = response.data.data.rows || []
      materialSearchPagination.total = response.data.data.total || 0
    } else {
      availableMaterials.value = []
      materialSearchPagination.total = 0
    }
    
    // 清空选中项
    if (selectMaterialTableRef.value) {
      selectMaterialTableRef.value.clearSelection()
    }
    selectedMaterial.value = null
  } catch (error) {
    console.error('搜索物料出错:', error)
    ElMessage.error('搜索物料出错，请稍后重试')
    availableMaterials.value = []
    materialSearchPagination.total = 0
  } finally {
    materialSearchLoading.value = false
  }
}

// 重置物料搜索条件
const resetMaterialSearch = () => {
  materialSearchForm.materialCode = ''
  materialSearchForm.materialName = ''
  materialSearchForm.materialTypeId = null
  materialSearchForm.batch = ''
  materialSearchForm.repositoryName = ''
  materialSearchForm.flatsMaterial = ''
  currentMaterialTypeId.value = null
  materialSearchPagination.currentPage = 1
  
  // 清除树形选中状态
  if (materialTypeTreeRef.value) {
    materialTypeTreeRef.value.setCurrentKey(null)
  }
  
  searchMaterials()
}

// 确认选择物料
const confirmSelectMaterial = () => {
  if (!selectedMaterial.value) {
    ElMessage.warning('请选择一个物料')
    return
  }
  
  // 将选中的物料信息填入表单
  const material = selectedMaterial.value
  singleMaterialForm.materialId = material.materialId || material.id
  singleMaterialForm.materialCode = material.materialCode
  singleMaterialForm.materialName = material.materialName
  singleMaterialForm.specification = material.specification
  singleMaterialForm.unit = material.unit
  singleMaterialForm.batchNo = material.batchNo || ''
  singleMaterialForm.transferSource = material.stockLocation || ''
  
  // 关闭物料选择对话框
  materialDialogVisible.value = false
}

// 确认添加单行物料
const confirmAddSingleMaterial = async () => {
  if (!singleMaterialForm.materialId) {
    ElMessage.warning('请选择物料')
    return
  }
  
  if (!singleMaterialForm.quantity || singleMaterialForm.quantity <= 0) {
    ElMessage.warning('请输入有效的转移数量')
    return
  }
  
  try {
    // 构建要添加的物料数据
    const materialData = {
      id: 0,
      allotId: formData.id,
      materialId: singleMaterialForm.materialId,
      batch: singleMaterialForm.batchNo || '',
      num: singleMaterialForm.quantity
    }


    console.log("添加物料数据",materialData);
    
    // 调用API添加物料
    await axios.post('/api/Allot/CreateAllotMaterial', materialData)
    

    ElMessage.success('添加物料成功')
    singleMaterialDialogVisible.value = false
    
    // 重新加载物料列表
    fetchMaterials()
  } catch (error) {
    console.error('添加物料出错:', error)
    ElMessage.error('添加物料出错，请稍后重试')
  }
}

// 删除单个物料
const handleDeleteMaterial = async (material) => {
  try {
    await ElMessageBox.confirm(
      '确认删除此产品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    console.log(material.materialId);
    
    // 调用API删除物料
    const response = await axios.post(`/api/Allot/DelAllotMaterial?ids=${material.materialId}`)
    
    ElMessage.success('删除产品成功')
    
    // 重新加载物料列表
    fetchMaterials()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除物料出错:', error)
      ElMessage.error('删除产品出错，请稍后重试')
    }
  }
}

// 批量删除物料
const handleBatchDeleteMaterial = async () => {
  if (selectedMaterialIds.value.length === 0) {
    ElMessage.warning('请至少选择一个产品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedMaterialIds.value.length} 个产品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 将ID数组转换为逗号分隔的字符串
    const ids = selectedMaterialIds.value.join(',')
    console.log(ids);
    
    // 调用API批量删除物料
    const response = await axios.post(`/api/Allot/DelAllotMaterial?ids=${ids}`)
    console.log(response);
    
    ElMessage.success('删除产品成功')
    
    // 重新加载物料列表
    fetchMaterials()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除物料出错:', error)
      ElMessage.error('批量删除产品出错，请稍后重试')
    }
  }
}

// 物料数量变化处理
const handleQuantityChange = async (value, material) => {
  try {
    // 调用API更新物料数量
    const response = await axios.post('/api/Allot/UpdateAllotMaterialQuantity', {
      id: material.materialId,
      allotId: formData.id,
      materialId: material.materialId,
      num: value
    })
    
    // 可以选择是否显示提示
    // ElMessage.success('更新数量成功')
  } catch (error) {
    console.error('更新物料数量出错:', error)
    ElMessage.error('更新物料数量出错，请稍后重试')
    // 恢复原来的数量
    fetchMaterials()
  }
}

// 执行上架
const handleDeploy = async (row) => {
  if (!row) {
    ElMessage.warning('请选择一条记录执行上架')
    return
  }
  
  if (row.status !== 1) {
    ElMessage.warning('只有待审核状态的转移单可以执行上架')
    return
  }
  
  dialogType.value = 'edit'
  deployMode.value = true // 设置为上架模式
  
  Object.keys(formData).forEach(key => {
    formData[key] = row[key]
  })
  autoGenerate.value = false
  dialogVisible.value = true
  
  // 加载物料数据
  await fetchMaterials()
}

// 单行物料表单
const singleMaterialForm = reactive({
  materialId: null,
  materialCode: '',
  materialName: '',
  specification: '',
  unit: '',
  quantity: 1,
  batchNo: '',
  transferSource: '',
  remark: ''
})

// 初始化
onMounted(() => {
  fetchMaterialTypeTree()
  fetchData()
})
</script>

<style scoped>
.allot-container {
  padding: 20px;
}

.layout-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 120px);
}

.tree-container {
  width: 250px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tree-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.tree-header h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 500;
}

.tree-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.code-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.auto-generate-switch {
  display: flex;
  align-items: center;
  margin-left: 10px;
  white-space: nowrap;
}

.switch-label {
  margin-right: 5px;
  color: #606266;
  font-size: 14px;
}

.ml-10 {
  margin-left: 10px;
}

.radio-container {
  height: 32px;
  display: flex;
  align-items: center;
}

.btn-cancel {
  border-radius: 4px;
  padding: 9px 20px;
}

.btn-save {
  border-radius: 4px;
  padding: 9px 20px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

:deep(.el-form-item__label::before) {
  color: #f56c6c;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  font-weight: bold;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
  margin: 0;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
}

:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

:deep(.el-radio) {
  margin-right: 30px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.allot-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.materials-container {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.materials-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.materials-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.materials-actions {
  display: flex;
  gap: 10px;
}

.materials-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.material-dialog-container {
  display: flex;
  gap: 20px;
  height: 500px;
}

.material-type-tree {
  width: 220px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tree-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tree-header h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 500;
}

.tree-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.material-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.material-search {
  margin-bottom: 15px;
}

:deep(.material-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.btn-deploy {
  border-radius: 4px;
  padding: 9px 20px;
}

.material-select-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.material-select-container .el-input {
  flex: 1;
}

:deep(.single-material-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-input-number.is-controls-right .el-input__wrapper) {
  padding-right: 25px;
}

:deep(.el-input-number--small) {
  width: 100%;
}

/* 美化对话框 */
:deep(.custom-dialog .el-dialog) {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

:deep(.custom-dialog .el-dialog__header) {
  background-color: #f5f7fa;
  padding: 18px 24px !important;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.custom-dialog .el-dialog__title) {
  font-weight: 600;
  font-size: 17px;
  color: #303133;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 28px 24px !important;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

:deep(.custom-dialog .el-dialog__footer) {
  border-top: 1px solid #e4e7ed;
  padding: 16px 24px !important;
}

:deep(.custom-dialog .el-button) {
  border-radius: 4px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.custom-dialog .el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.custom-dialog .el-form-item__label) {
  font-weight: 500;
  color: #303133;
  padding-right: 12px !important;
}

:deep(.custom-dialog .el-input__wrapper) {
  border-radius: 4px;
  transition: all 0.3s;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.custom-dialog .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.custom-dialog .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.custom-dialog .el-form-item) {
  margin-bottom: 24px !important;
}

:deep(.custom-dialog .el-textarea__inner) {
  border-radius: 4px;
}

/* 编辑对话框标题样式 */
.edit-dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

/* 添加产品列表样式 */
.product-list-container {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.product-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.product-list-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.product-list-actions {
  display: flex;
  gap: 10px;
}

.material-select-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.material-select-container .el-input {
  flex: 1;
}

.material-dialog-container {
  display: flex;
  gap: 24px;
  height: 520px;
}

.material-type-tree {
  width: 240px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f9fafc;
  border-radius: 6px;
}

.tree-header {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.tree-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.tree-content {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
}

:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 4px;
  margin-bottom: 2px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f0f2f5;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
}

.material-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.material-search {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
}

:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 10px 0;
}

:deep(.el-table--border th:first-child, .el-table--border td:first-child) {
  border-left: none;
}

:deep(.el-table--border th:last-child, .el-table--border td:last-child) {
  border-right: none;
}

.materials-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 美化单行物料对话框 */
.single-material-dialog :deep(.el-form-item) {
  margin-bottom: 20px !important;
}

.single-material-dialog :deep(.el-form-item__label) {
  font-weight: 500;
}

/* 美化操作按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer .el-button {
  min-width: 100px;
}
</style>
